import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';

const $api = require("../../../../request/api").API
Page({
	data: {
		selectionDialog: {
			show: false,
			data: [],
			selectedOptions: undefined,
			selectedOptionsIndex: 0
		},
		history: [],
		fireDesc: '',
		address: "",
		beeperId: "",
		selectorShow: false,
		selectedOptions: [],
		video: '',
		videoBase64: '',
		residentAddress: {
			fieldNames: {
				text: "name",
				value: "id"
			},
			name: '',
			columns: [],
		}
	},
	onLoad: function (options) {
		const {
			beeperId
		} = options
		this.setData({
			beeperId
		})
		this.fetchResidentAddressList()
		this.handleObtainInitialData(beeperId)
		this.getAddress(beeperId)
	},

	/**
	 * 获取初始数据
	 */
	handleObtainInitialData(beeperId) {
		Toast.loading({
			message: '加载中...',
			forbidClick: true
		});
		$api.getBeeperDetectionList({
			beeperId
		}).then(res => {
			const {
				data,
				status
			} = res.data
			if (status === 0) {
				if (data.length > 0) {
					this.setData({
						'selectionDialog.data': data,
						'selectionDialog.show': true
					});
				}
			}
			Toast.clear()
		}).catch(() => {
			Toast.clear()
		})
	},

	/**
	 * 发送上报
	 */
	handleSendReport() {
		const {
			selectedOptions,
			residentAddress,
			address,
			fireDesc,
			videoBase64,
			beeperId
		} = this.data

		if (residentAddress.name == '' && address == '') {
			Toast.fail("所在楼层或详细位置必须填写一个")
			return false
		}
		if (videoBase64 == "" && fireDesc == "") {
			Toast.fail("灾情描述或上传视频必须填写一个")
			return false
		}
		const params = {
			beeperId: beeperId,
			fireDesc: fireDesc,
			fireVideos: videoBase64,
			site: address
		}
		if (selectedOptions.length >= 1 && selectedOptions[0].id) {
			params.buildId = selectedOptions[0].id
			params.buildName = selectedOptions[0].name
		}
		if (selectedOptions.length >= 2 && selectedOptions[1].id) {
			params.unitId = selectedOptions[1].id
			params.unitName = selectedOptions[1].name
		}
		if (selectedOptions.length >= 3 && selectedOptions[2].id) {
			params.floorId = selectedOptions[2].id
			params.floorName = selectedOptions[2].name
		}
		if (selectedOptions.length >= 4 && selectedOptions[3].id) {
			params.houseNumberId = selectedOptions[3].id
			params.houseNumber = selectedOptions[3].name
		}

		Toast.loading({
			message: '提交中...',
			forbidClick: true,
		});
		$api.addFireDetection(params).then(res => {
			Toast.success("提交成功")
			setTimeout(() => {
				wx.navigateBack({
					delta: 1
				})
			}, 800)
		}).catch(err => {
			Toast.fail(err.msg || '提交失败')
		})
	},



	/**
	 * 选择视频
	 */
	handleSelectAddVideo() {
		wx.chooseMedia({
			count: 1,
			mediaType: ['video'],
			sourceType: ['album', 'camera'],
			maxDuration: 30,
			camera: 'back',
			success: res => {
				let tempFilePath = res.tempFiles[0].tempFilePath
				const videoBase64 = wx.getFileSystemManager().readFileSync(res.tempFiles[0].tempFilePath, "base64")
				this.setData({
					video: tempFilePath,
					videoBase64
				})
			}
		})
	},

	/**
	 * 获取该小区下的楼顶至门牌号
	 */
	fetchResidentAddressList() {
		const {
			beeperId
		} = this.data
		$api.getResidentAddressList({
			beeperId
		}).then(res => {
			this.setData({
				'residentAddress.columns': res.data.data
			})
		})
	},

	/**
	 * 楼栋选择器选择
	 */
	handleResidentAddressChange(e) {
		const {
			selectedOptions
		} = e.detail;
		console.log(e.detail)
		const fieldValue = selectedOptions
			.map((option) => option.text || option.name)
			.join('/');
		console.log(fieldValue, "fieldValuefieldValuefieldValue")

		this.setData({
			'residentAddress.name': fieldValue,
			selectedOptions: e.detail.selectedOptions.map(c => {
				return {
					id: c.id,
					name: c.name
				}
			})
		})
	},

	/**
	 * 清空楼栋层选择数据
	 */
	handleWipeOptionData() {
		this.setData({
			'residentAddress.name': '',
			selectedOptions: []
		})
	},

	/**
	 * 打开楼栋层选择器
	 */
	showResidentAddressPopup() {
		this.setData({
			selectorShow: true
		})
	},

	/**
	 * 关闭楼栋层选择器
	 */
	closeResidentAddress(e) {
		const type = e.currentTarget.dataset.type
		const {
			selectedOptions
		} = this.data
		if (type == 1) {
			if (selectedOptions.length == 0) {
				this.setData({
					selectorShow: false
				})
				return false
			}
			const [buildOption, unitOption, floorOption, houseNumberOption] = selectedOptions;
			const buildId = buildOption?.id || '';
			const unitId = unitOption?.id || '';
			const floorId = floorOption?.id || '';
			const houseNumberId = houseNumberOption?.id || '';
			$api.getHouseNumberDetectionList({
				buildId: buildId,
				floorId: floorId,
				houseNumberId: houseNumberId,
				unitId: unitId,
			}).then(res => {
				const {
					data,
					status
				} = res.data
				if (status === 0) {
					if (data.length > 0) {
						this.dialogTip(2)
					}
				}
			})
			this.setData({
				selectorShow: false
			})
		} else {
			this.setData({
				selectorShow: false
			})
		}
	},

	/**
	 * 输入框输入
	 * @param e
	 */
	handleTextareaInput(e) {
		const {
			remark
		} = e.target.dataset
		if (remark === 'address') this.setData({
			address: e.detail.value
		})
		if (remark === 'fireDesc') this.setData({
			fireDesc: e.detail.value
		})
	},

	/**
	 * 清除视频
	 */
	handleClearVideo() {
		this.setData({
			video: ''
		})
	},

	/**
	 * 消防报警列表
	 */
	handleDialogConfirm() {
		this.dialogTip(1)
	},

	handleDialogClose() {
		wx.navigateBack({
			delta: 1
		})
	},

	getAddress(id) {
		$api.getUserBeeperAddress({
			beeperId: id
		}).then(res => {
			if (res.data.status == 0) {
				const {
					buildName,
					unitName,
					floorName,
					houseNumber,
					buildId,
					unitId,
					floorId,
					houseNumberId
				} = res.data.data;
				this.setData({
					'residentAddress.name': `${buildName}/${unitName}/${floorName}/${houseNumber}`,
					selectedOptions: [{
							id: buildId,
							name: buildName
						},
						{
							id: unitId,
							name: unitName
						},
						{
							id: floorId,
							name: floorName
						},
						{
							id: houseNumberId,
							name: houseNumber
						}
					]
				});
			}
		})
	},

	dialogTip(type) {
		if (type == 1) {
			return false
		}
		Dialog.confirm({
				title: '提示',
				confirmButtonText: '继续',
				cancelButtonText: '取消',
				message: `已存在相同地址报警记录，是否继续新增`
			}).then(() => {
				if (type == 1) {
					this.setData({
						'selectionDialog.show': false
					});
				}
			})
			.catch(() => {
				wx.navigateBack({
					delta: 1
				})
			});
	}
});